<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace backend\controllers;

use builder\base\BaseController;
use builder\form\FormBuilder;
use builder\helper\H5;
use builder\tree_table\TreeTableBuilder;
use common\models\Region;
use common\models\RegionService;

/**
 * 地区
 * @auther 荒
 * @since 1.0.0
 * @datetime 2023.10.25 14:52
 */
class RegionController extends BaseController
{
    public $actionVerbs = [
        'view' => ['GET'],
        'update' => ['GET', 'POST'],
        'sort' => ['POST'],

        'cascade' => ['GET'],
    ];
    public $publicActions = ['cascade'];
    public $undetectedActions = ['children'];

    /**
     * 顶级节点列表
     * @return string
     * @throws \yii\base\InvalidConfigException
     */
    public function actionView()
    {
        $treeTable = TreeTableBuilder::instance(['id' => 'region_view']);
        if ($this->isAjax) {
            $treeTable->setQuery(function () {
                $query = Region::query()->where(['pid' => 0]);
                $queryParams = $this->filteredGet;
                $query->andFilterWhere([
                    'or',
                    ['like', 'name', isset($queryParams['keyword']) ? $queryParams['keyword'] : null],
                    ['like', 'letter', isset($queryParams['keyword']) ? $queryParams['keyword'] : null],
                ]);

                return $query;
            })->setOrderBy([
                'sort' => SORT_DESC,
                'id' => SORT_ASC,
            ])->setTtColumns([
                'id',
                'pid',
                'name',
                'letter',
                'sort',
                'isParent' => 1,
                'status' => function ($row) {
                    return H5::text(
                        $row['status'] ? '✔' : '╳',
                        ['class' => 'f18 text-' . ($row['status'] ? 'primary' : 'danger')]
                    );
                },
            ]);
        } else {
            $treeTable->setTitle('地区列表')
                ->setMaxHeight(780)
                ->setLimit(20)
                ->setTreeCustomNameOption([
                    'pid' => 'pid',
                ])
                ->setTreeAsyncOption('region/children', [
                    'autoParam' => ['id=id', 'pid']
                ])
                ->setTreeDataOption([
                    'rootPid' => 0,
                ])
                ->setTreeViewOption([
                    'iconLeaf' => '',
                ])
                ->setTreeTableHead([
                    $this->treeTableHead->field('id')->title('ID')->sort(),
                    $this->treeTableHead->field('name')->title('名称'),
                    $this->treeTableHead->field('sort')->title('排序')->editText('region/sort')->width(150),
                    $this->treeTableHead->field('letter')->title('首字母')->width(80),
                    $this->treeTableHead->field('status')->title('状态')->width(100),
                    $this->treeTableHead->toolbar()->title('操作项')->width(120),
                ])
                ->setTtToolbarFilter([
                    'keyword' => $this->ttToolbarFilter->text()->label('关键词')->uiClass('w-300 pr-3'),
                ])
                ->setTtRowOperation([
                    $this->ttRowOperation->modal()->title('编辑')->route('region/update')->height(380),
                ]);
        }

        return $treeTable->render();
    }

    /**
     * 子节点
     * @param int $id ID
     * @param int $pid 父ID
     * @return string
     */
    public function actionChildren($id, $pid)
    {
        $isParent = $pid == 0;
        $all = Region::query(['id', 'pid', 'name', 'letter', 'sort', 'status'])
            ->where(['pid' => $id])
            ->orderBy([
                'sort' => SORT_DESC,
                'id' => SORT_ASC,
            ])
            ->all();
        foreach ($all as &$item) {
            $item['isParent'] = $isParent;
            $item['status'] = H5::text(
                $item['status'] ? '✔' : '╳',
                ['class' => 'f18 text-' . ($item['status'] ? 'primary' : 'danger')]
            );
        }
        return $this->asOk('success', [
            'count' => count($all),
            'list' => $all,
        ]);
    }

    /**
     * 编辑
     * @param int $id ID
     * @return FormBuilder|string
     */
    public function actionUpdate($id)
    {
        $model = Region::findOne($id);
        if ($this->isPost) {
            $model->setScenario('region_edit');
            $model->load($this->post);
            if ($model->save()) {
                return $this->asOk('编辑成功' . "#$id");
            }

            return $this->asFail($model->error . "#$id");
        } else {
            return FormBuilder::instance(['id' => 'region_update'])
                ->setPartial()
                ->setTitle('编辑')
                ->setFormControl([
                    'name' => $this->formControl->text()->label('名称')->required()->defaultValue($model->name),
                    'sort' => $this->formControl->number()->label('排序')->required()->defaultValue($model->sort),
                    'status' => $this->formControl->sw()->label('状态')->required()->checked(!!$model->status),
                ])
                ->setCloseBtn()
                ->setSubmitBtn()
                ->setAutoClose()
                ->setSubmittedCalls([
                    'parent' => 'region_view',
                ])
                ->render();
        }
    }

    /**
     * 排序
     * @param int $id ID
     * @return string
     */
    public function actionSort($id)
    {
        $model = Region::findOne($id);
        if (empty($model)) {
            return $this->asFail('ID错误!');
        }

        $model->setScenario('region_sort');
        $model->load($this->post);
        if ($model->save()) {
            return $this->asOk('排序成功' . "#{$id}");
        }

        return $this->asFail($model->error . "#{$id}");
    }

    /**
     * 级联动
     * @return string
     */
    public function actionCascade()
    {
        $queryParams = $this->filteredGet;
        if (!empty($queryParams['province'])) {
            $region = Region::findOne(['name' => $queryParams['province'], 'level' => 1]);
            if (empty($region)) {
                return $this->asFail('参数[province]值错误');
            }

            $id = $region->id;
        } elseif (!empty($queryParams['city'])) {
            $region = Region::findOne(['name' => $queryParams['city'], 'level' => 2]);
            if (empty($region)) {
                return $this->asFail('参数[city]值错误');
            }

            $id = $region->id;
        } else {
            return $this->asFail('未发现有效参数');
        }

        return $this->asOk('Success', RegionService::getCascadeByPid($id));
    }
}